//send simple message by dingtalk / email / bark ...
import download from './download.js'
import crypto from 'crypto'
import nodemailer from 'nodemailer'

export const dingding = (token, secret, text, desc) => {
  return new Promise(async (resolve, reject) => {
    let url = `https://oapi.dingtalk.com/robot/send?access_token=${token}`;
    let data = {
      msgtype: 'text',
      text: {
        content: `${text}\n\n${desc}`,
      },
    };
    if (token && secret) {
      const dateNow = Date.now();
      const hmac = crypto.createHmac('sha256', secret);
      hmac.update(`${dateNow}\n${secret}`);
      const result = encodeURIComponent(hmac.digest('base64'));
      url = `${url}&timestamp=${dateNow}&sign=${result}`;

    }
    let ins = new download(url);
    try {
      let rst = await ins.post(data);
      if (rst.errcode === 0) {
        resolve(true);
      } else {
        reject(rst.errmsg);
      }
    } catch (err) {
      reject('Send message failed : Dingtalk')
    }
  });

}

export const mail = async (smtpHost,port,baseUser,basePass,userList,title,content) => {
  // create reusable transporter object using the default SMTP transport
  var transporter = nodemailer.createTransport({
    pool: true,
    host: smtpHost,
    port: port,
    secure: true,
    auth: {
      user: baseUser,
      pass: basePass
    },
    tls: {
      // do not fail on invalid certs
      rejectUnauthorized: false,
    },
  });

  // setup e-mail data with unicode symbols
  var mailOptions = {
    from: 'BUG<'+baseUser+'>', // sender address
    to: userList.join(','), // list of receivers
    subject: title, // Subject line
    html: content // html body
  };
  let info;
  try {
    info = await transporter.sendMail(mailOptions);  
  } catch (err) {
    console.log(err);
  }
  return info;
}